package com.godme.code.service.impl;

import com.godme.code.service.CodeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@RefreshScope
@Component
public class CodeServiceImpl implements CodeService {

    private final String code = "code";


    @Value("${code.expire:30}")
    private Integer expire;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public String generate(String mail) {
        String code = generateCode();
        redisTemplate.opsForValue().set(mail, code,expire,TimeUnit.SECONDS);
        return code;
    }


    private String generateCode(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public int validCode(String mail, String code) {
        String lastCode = redisTemplate.opsForValue().get(mail);
        if(Objects.isNull(lastCode)){
            return 2;
        }
        return (Objects.nonNull(code) && code.equalsIgnoreCase(lastCode))? 0 : 1;
    }
}
